/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        int i = removeNthFromEnd0(head, n);
        if (i == n) {
            return head.next;
        }
        return head;
    }

    public int removeNthFromEnd0(ListNode head, int n) {
        if (head == null) {
            return 0;
        }
        int endIndex = removeNthFromEnd0(head.next, n);
        if (endIndex == n) {
            head.next = head.next == null ? null : head.next.next;
        }
        return endIndex + 1;
    }
}